
#include <iostream>
// using namespace std;

#include <boost/smart_ptr.hpp>
#include <boost/smart_ptr/make_unique.hpp>
using namespace boost;

static void case1()
{
    // 不可被复制，离开作用域则销毁
    scoped_ptr<std::string> sp(new std::string("text"));

    assert(sp);
    assert(sp != nullptr);

    std::cout<<*sp<<std::endl;
    std::cout<<sp->size()<<std::endl;
}

struct posix_file
{
    posix_file(const char *file_name)
    {
        std::cout<<"open file:"<<file_name<<std::endl;
    }

    ~posix_file()
    {
        std::cout<<"close file"<<std::endl;
    }
};

static void case2()
{
    scoped_ptr<posix_file> fp(new posix_file("/tmp/a.txt"));
    scoped_ptr<int> p(new int);

    if (p)
    {
        *p = 100;
        std::cout<<*p<<std::endl;
    }

    p.reset();
    assert(0 == p);
    if (!p)
    {
        std::cout<<"scoped_ptr == nullptr"<<std::endl;
    }
}

class ptr_owned final
{
    scoped_ptr<int> m_ptr;
};

static void bad_case()
{
    scoped_ptr<std::string> sp(new std::string("text"));
}

static void case_unique()
{
    // unique_ptr指向的堆内存无法同其它unique_ptr共享
    auto p = boost::make_unique<int>(10); // 创建unique_ptr
    assert(p && *p == 10);
    p.release();
    assert(!p);

    auto a = boost::make_unique<int[]>(5);
    a[0] = 100;
    a[4] = 500;
    std::cout<<a[0]<<"\t"<<a[4]<<std::endl;
}

int main()
{
    // case1();
    // case2();
    // bad_case();
    case_unique();
}
